/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bankingsystem;

import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *this class responsible for creating new accounts, creating new customers , creating new Staff member functions.
 * @author  Hasitha Aravinda
 * 
 */
public class StaffFrontEnd {

    /**
     * reference objects
     */
    private Bank bank;                  // Banking System Bank object
    private BankInterface parentMenu;   // parent menu object
    private Customer currentCustomer;   // current
    private Staff logedStaff;       // currently logged staff member

    /**
     * Constructor with input parameters
     * @param bank is a Bank.
     * @param bi is a BankInterface.
     */
    public StaffFrontEnd(Bank bank, BankInterface bi) {
        currentCustomer = null;
        logedStaff = null;
        this.bank = bank;
        this.parentMenu = bi;
        start();
    }

    /**
     *method for start Terminal
     */
    public void start() {
        if (Login()) {
            // if login success
            showMenu();
        } else {
            //login failed, back to main menu.
            this.parentMenu.init(); // back to the main menu
            try {
                this.finalize(); // dispose object
            } catch (Throwable ex) {
                System.err.println("Unexpected Error occured ");
            }
        }

    }

    /*
     *method for show Staff menu
     *
     */
    private void showMenu() {
        boolean menuShow = true;


        while (menuShow) {
            System.out.println("-------Staff Menu-------");
            System.out.println("Select an option");
            System.out.println("1: create new User");
            System.out.println("2: create new Account");
            System.out.println("3: create new Staff Member");
            System.out.println("4: Save Data");
            System.out.println("5: Back to main menu");
            System.out.println("0: Exit");
            System.out.print("\nSelect your choice :");
            Scanner sc = new Scanner(new InputStreamReader(System.in));
            int choice = 0;

            //  read the choice from the command-line;
            try {
                choice = sc.nextInt();
            } catch (Exception ioex) {
                System.out.println("IO error while reading data!");
            }

            switch (choice) {
                case 1:
                    //code :create new user
                    this.createUser();
                    break;
                case 2:
                    //code :create new account
                    this.createAccount();
                    break;
                case 3:
                    //code : create new staff member
                    this.createStaff();
                    break;
                case 4:
                    //code : save Bank object
                    new PersistenceManager().savedata(bank);
                    break;
                case 5:
                    //code : back to main menu
                    this.parentMenu.init();
                    try {
                        this.finalize();
                    } catch (Throwable ex) {
                    }
                    break;
                case 0:
                    //exit
                    System.out.println("Thank for Using the system");
                    System.exit(0);
                    break;

                default:
                    //code for invalid input
                    System.err.println("\nInvalied input:");
            }//end of switch

        }
    }

    /**
     *method for login for staff members:
     */
    public boolean Login() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Staff temp = null;
        System.out.println("Enter Login Details:");
        System.out.print("\nUser Name:");
        String answer = "";

        //  read the answer from the command-line;
        try {
            answer = br.readLine();
        } catch (IOException ioex) {
            System.out.println("IO error while reading choice!");
        }

        //creating tempory Staff member
        temp = bank.getStaff().get(answer);
        if (temp != null) {
            System.out.print("Password:");

            //  read the answer from the command-line;
            try {
                answer = br.readLine();
            } catch (IOException ioex) {
                System.out.println("IO error while reading choice!");
            }

            if (temp.checkPassword(answer)) {
                //login success
                this.logedStaff = temp;
                System.out.println("\nWelcome " + logedStaff.getName());
                return true;
            } else {
                //login fail due to wring password
                System.out.println("Wrong User name or password");
                this.logedStaff = null;
                return false;
            }
        } else {
            System.out.println("Login Fail: ");
            return false;
        }


    }

    /**
     *  method for user identification:
     */
    public boolean IdentifyUser(String CustomerID) {
        Customer temp = bank.getCustomers().get(CustomerID);
        if (temp == null) {
            //no Customer found
            return false;
        } else {
            // customer Exists
            currentCustomer = temp;
            return true;
        }

    }

    /**
     * method for show menu for create accounts
     * procedure for create account:
     * step 1) Identify user
     * step 2) select account type
     * step 3) create account
     */
    public void createAccount() {
        Scanner sc = new Scanner(new InputStreamReader(System.in));
        String name = "";
        System.out.print("Enter CustomerID:");

        try {
            name = sc.nextLine();
        } catch (Exception ex) {
            System.out.println("IO error while reading choice!");
        }
        if (IdentifyUser(name)) {
            System.out.println("Select account type:");
            System.out.println("1 : fixed account");
            System.out.println("2 : Current account");
            System.out.println("3 : Saving account");
            System.out.println("4 : Loan");
            System.out.print("Select yours choice :");

            int choice = 0;
            //  read the choice from the command-line;
            try {
                choice = sc.nextInt();
            } catch (Exception ioex) {
                System.out.println("IO error while reading choice!");
            }

            switch (choice) {
                case 1:
                    //code for fixed create account
                    createFixedAccount();
                    break;
                case 2:
                    //code for create current account
                    createCurrentAccount();
                    break;
                case 3:
                    //code for create saving account
                    createSavingAccount();
                    break;
                case 4:
                    //code for create loan account
                    this.createLoanAccount();
                    break;
                default:
                    //code for invalid input
                    System.out.println("Invalied input:");
            }//end of switch

        } else {
            System.out.println("No user Found");

        }
    }

    /**
     * method for create Loan account:
     *///
    public void createLoanAccount() {
        //array for store data:
        String[][] details = new String[][]{{"Loan No", "Amount Rs:", "Interest Rate %", "Duration(in Months)"}, {"", "", "", ""}};
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Loan temp;
        String value = "";
        System.out.println("Enter follwing Details:");

        //  reading the data from the command-line and store them in array
        try {
            for (int i = 0; i < details[0].length; i++) {
                System.out.print("Enter " + details[0][i] + " :");
                value = br.readLine();
                if (value.equals("")) {
                    System.err.println(details[0][i] + " can't be empty, re-enter value");
                    i = i - 1;
                    continue;
                }
                details[1][i] = value;
            }
        } catch (IOException ioex) {
            System.err.println("IO error while reading data!");
        }


        try {
            // Reference from Loan class:
            //: Loan(int loanNo, double amount, Customer customer, double interestRate, Date startingDate, int duration)
            //creating Savinf account Object
            temp = new Loan(Integer.parseInt(details[1][0]), Double.parseDouble(details[1][1]), currentCustomer, Double.parseDouble(details[1][2]), new Date(), Integer.parseInt(details[1][3]));
            //temp should be added to bank class:
            bank.addLoan(temp);
            System.out.println("Loan Account " + temp.getLoanNo() + " is Created");
        } catch (Exception ex) {
            System.out.println("Error While Creating an Account");

        }



    }

    /**
     * method for create saving account:
     *///
    public void createSavingAccount() {
        //array for store data:
        String[][] details = new String[][]{{"Account No", "Balance Rs:", "Interest %"}, {"", "", ""}};
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        SavingsAccount temp;
        String value = "";
        System.out.println("Enter follwing Details:");

        //  reading the data from the command-line and store them in array
        try {
            for (int i = 0; i < details[0].length; i++) {
                System.out.print("Enter " + details[0][i] + " :");
                value = br.readLine();
                if (value.equals("")) {
                    System.err.println(details[0][i] + " can't be empty, re-enter value");
                    i = i - 1;
                    continue;
                }
                details[1][i] = value;
            }
        } catch (IOException ioex) {
            System.err.println("IO error while reading data!");
        }


        try {
            //Reference from saving account:SavingsAccount(String accountNo,Customer customer,float balance,Date startDate, float interest){
            //creating Savinf account Object
            temp = new SavingsAccount(details[1][0], currentCustomer, Float.parseFloat(details[1][1]), Calendar.getInstance(), Float.parseFloat(details[1][2]));
            //adding temp into bank class:
            bank.addSavingsAccount(temp);
            System.out.println("Saving Account " + temp.accountNo + " is Created");
        } catch (Exception ex) {
            System.err.println("Error While Creating an Account");

        }

    }

    /**
     * method for create current account:
     *///
    public void createCurrentAccount() {
        //array for store data:
        String[][] details = new String[][]{{"AccountNo", "Balance Rs: ", "Over Draft Rs: "}, {"", "", ""}};
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        CurrentAccount temp;
        String value = "";
        System.out.println("Enter follwing Details:");

        //  reading the data from the command-line and store them in array
        try {
            for (int i = 0; i < details[0].length; i++) {
                System.out.print("Enter " + details[0][i] + " :");
                value = br.readLine();
                if (value.equals("")) {
                    System.err.println(details[0][i] + " can't be empty, re-enter value");
                    i = i - 1;
                    continue;
                }
                details[1][i] = value;
            }
        } catch (IOException ioex) {
            System.err.println("IO Error while reading data!");
        }


        try {
            //Reference: CurrentAccount(String accountNo,Customer customer,float balance,Calendar startDate, float ol){
            //creating
            temp = new CurrentAccount(details[1][0], currentCustomer, Float.parseFloat(details[1][1]), Calendar.getInstance(), Float.parseFloat(details[1][2]));
            //temp should be added to bank class:
            bank.addCurrentAccount(temp);
            System.out.println("Current Account " + temp.accountNo + " is Created");
        } catch (Exception ex) {
            System.err.println("Error While Creating an Account");

        }



    }

    /**
     * method for create Fixed account:
     */
    public void createFixedAccount() {
        //array for store data:
        String[][] details = new String[][]{{"AccountNo", "Balance Rs :", "Duration(in months)", "Interest Rate %"}, {"", "", "", ""}};
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        FixedAccount temp;
        String value = "";

        System.out.println("Enter follwing Details:");

        //  reading the data from the command-line and store them in array
        try {
            for (int i = 0; i < details[0].length; i++) {
                System.out.print("Enter " + details[0][i] + " :");
                value = br.readLine();
                if (value.equals("")) {
                    System.out.println(details[0][i] + " can't be empty, re-enter value");
                    i = i - 1;
                    continue;
                }

                details[1][i] = value;
            }
        } catch (IOException ioex) {
            System.out.println("IO error while reading data!");
        }

        try {
            //Reference: public FixedAccount(String accountNo, Customer customer, float balance, Calendar startDate, int duration, float interestRate) {
            //creating custFixedAccountomer object
            temp = new FixedAccount(details[1][0], currentCustomer, Float.parseFloat(details[1][1]), Calendar.getInstance(), Integer.parseInt(details[1][2]), Float.parseFloat(details[1][3]));
            bank.addFixedAccount(temp);
            System.out.println("Fixed Account " + temp.accountNo + " is Created");
        } catch (Exception ex) {
            System.out.println("Error While Creating an Account");

        }



    }

    /**
     * method for create new User:
     */
    public void createUser() {

        //array for store data of:
        String[][] details = new String[][]{{"Name", "Customer ID", "Password", "Address", "TeleNo", "NIC no"}, {"", "", "", "", "", ""}};
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String value = "";
        System.out.println("\nEnter follwing Details:");

        //  reading the data from the command-line and store them in array
        try {
            for (int i = 0; i < details[0].length; i++) {
                System.out.print("Enter " + details[0][i] + " :");
                value = br.readLine();
                //check for empty strings: if it empty allow to retype it again
                if (value.equals("")) {
                    System.out.println(details[0][i] + " can't be empty, re-enter value");
                    i = i - 1;
                    continue;
                }
                details[1][i] = value;
            }
        } catch (IOException ioex) {
            System.out.println("IO error while reading data!");
        }

        try {
            //creating customer object
            Customer temp = new Customer(details[1][0], details[1][1], details[1][3],
                    (int) Integer.parseInt(details[1][4]), details[1][5], details[1][2]);
            //temp added to bank :
            bank.addCustomer(temp);
            System.out.println("User " + temp.getCustomerID() + " is Created");
        } catch (Exception ex) {
            //handeling Exceptions
            System.out.println("Error While Creating an User");

        }

    }

    /**
     * method for create new Staff member:
     */
    public void createStaff() {
        //Reference : public Staff(String name, String nic, String employe_id, String password, String position)
        //array for store data of:
        String[][] details = new String[][]{{"Name", "nic", "employe_id", "password", "position"}, {"", "", "", "", ""}};
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String value = "";
        System.out.println("\nEnter follwing Details:");

        //  reading the data from the command-line and store them in array
        try {
            for (int i = 0; i < details[0].length; i++) {
                System.out.print("Enter " + details[0][i] + " :");
                value = br.readLine();
                //check for empty strings: if it empty allow to retype it again
                if (value.equals("")) {
                    System.out.println(details[0][i] + " can't be empty, re-enter value");
                    i = i - 1;
                    continue;
                }
                details[1][i] = value;
            }
        } catch (IOException ioex) {
            System.out.println("IO error while reading data!");
        }

        try {
            //creating customer object
            Staff temp = new Staff(details[1][0], details[1][1], details[1][2], details[1][3], details[1][4]);
            //temp added to bank :
            bank.addStaff(temp);
            System.out.println("User " + temp.getEmployeeID() + " is Created");
        } catch (Exception ex) {
            //handeling Exceptions
            System.out.println("Error While Creating an User");

        }

    }
} // end of class

